<template>
  <div v-loading="getDetailLoading" class="order_module_detail" element-loading-text="加载中...">
    <div class="header">
      <div class="info_container">
        <div class="title_container">
          <div class="title">
            <i class="iconfont icon-detail"></i>
            <div class="name">
              工单模块名称:
              <span>{{ form.name }}</span>
            </div>
          </div>
          <HStatus v-if="!form.status">启用</HStatus>
          <HStatus v-else type="info">禁用</HStatus>
        </div>
        <div class="info_list">
          <div class="info_item">
            <div class="label">模块类型:</div>
            <div class="value">
              <template v-if="form.type === 1">安装</template>
              <template v-else-if="form.type === 2">维修</template>
              <template v-else-if="form.type === 3">保养</template>
              <template v-else>其他</template>
            </div>
          </div>
          <div class="info_item">
            <div class="label">模块质保状态:</div>
            <div class="value">
              <template v-if="form.overinsured">保外</template>
              <template v-else>保内</template>
            </div>
          </div>
          <div class="info_item">
            <div class="label">创建时间:</div>
            <div class="value">{{ form.createTime ? form.createTime : '' }}</div>
          </div>
          <div class="info_item">
            <div class="label">更新时间:</div>
            <div class="value">{{ form.updateTime ? form.updateTime : '' }}</div>
          </div>
        </div>
      </div>

      <!-- 按钮组 -->
      <div class="btn_group">
        <HPlainButton :color="PRIMARY_COLOR" @click="editModule">编辑</HPlainButton>
        <HPlainButton type="error" @click="deleteModule">删除</HPlainButton>
      </div>
    </div>

    <div ref="infoListRef" class="info_list">
      <div class="info_item_container">
        <div class="info_item">
          <div class="label">保内费用:</div>
          <div class="value">￥{{ form.inSourcingPrice }}</div>
        </div>
        <div class="info_item">
          <div class="label">保外费用:</div>
          <div class="value">￥{{ form.outSourcingPrice }}</div>
        </div>
        <div class="info_item">
          <div class="label">质保日期:</div>
          <div class="value">{{ form.warrantyDay }}天</div>
        </div>
      </div>
      <div class="info_item_container">
        <div class="info_item">
          <div class="label" style="width: 64px; text-align: right">预约时间:</div>
          <div class="value">
            <template v-if="form.reservationTimeType === 1"> 不启用 </template>
            <template v-if="form.reservationTimeType === 2"> 24小时 </template>
            <template v-if="form.reservationTimeType === 3">
              {{ form.reservationStartTime }}~{{ form.reservationEndTime }}
            </template>
          </div>
        </div>
        <div class="info_item">
          <div class="label" style="width: 64px; text-align: right">工单质保:</div>
          <div class="value">
            <template v-if="form.enableWarrantyOrder">启用</template>
            <template v-else>禁用</template>
          </div>
        </div>
        <div class="info_item">
          <div class="label" style="width: 64px; text-align: right">移动端可见:</div>
          <div class="value">
            <template v-if="form.mobileCreateOrderShow">显示</template>
            <template v-else>隐藏</template>
          </div>
        </div>
      </div>
      <div class="info_item_container">
        <div class="info_item">
          <div class="label" style="width: 64px; text-align: right">结单核销码:</div>
          <div class="value">
            <template v-if="form.enableStatementVerifCode">启用</template>
            <template v-else>关闭</template>
          </div>
        </div>
        <div class="info_item">
          <div class="label" style="width: 64px; text-align: right">核销码方式:</div>
          <div class="value">
            <template v-if="form.enableStatementVerifCode">
              <template v-if="form.statementVerifCodeType === 1">随机</template>
              <template v-else>固定</template>
            </template>
          </div>
        </div>
        <div class="info_item">
          <div class="label" style="width: 64px; text-align: right">SLA规则:</div>
          <div class="value">{{ form.slaName || '空' }}</div>
        </div>
      </div>
      <div class="info_item_container">
        <div class="info_item">
          <div class="label" style="width: 75px; text-align: right">分配客服方式:</div>
          <div class="value">
            <template v-if="form.autoDispatchClient"> 自动分配 </template>
            <template v-else>人工分配</template>
          </div>
        </div>
        <div class="info_item">
          <div class="label" style="width: 75px; text-align: right">分配客服规则:</div>
          <div class="value">
            <template v-if="form.autoDispatchClient">
              <template v-for="item in clientStrategyOption">
                <template v-if="item.id === form.workClientStrategyId">
                  {{ item['name'] }}
                </template>
              </template>
              <!-- 自动分配 -->
            </template>
            <template v-else>空</template>
          </div>
        </div>
        <div class="info_item">
          <div class="label" style="width: 75px; text-align: right">拨打电话:</div>
          <div class="value">
            <template v-if="form.callPhoneType == 0">关闭</template>
            <template v-else>必须拨打</template>
          </div>
        </div>
        <!-- <el-form-item label="分派网点方式:">
              <span v-if="form.autoDispatchNetwork">自动派单</span>
              <span v-else>人工派单</span>
            </el-form-item> -->
      </div>
      <!-- <div>
            <el-form-item label="分派网点规则:">
            空
            </el-form-item>
          </div> -->
      <div class="info_item_container">
        <div class="info_item">
          <div class="label">开启签到:</div>
          <div class="value">
            <template v-if="form.enableSign">启用</template>
            <template v-else>关闭</template>
          </div>
        </div>
        <div class="info_item">
          <div class="label">工单挂起:</div>
          <div class="value">
            <template v-if="form.enableSuspend">启用</template>
            <template v-else>关闭</template>
          </div>
        </div>
        <div class="info_item">
          <div class="label">模块归属:</div>
          <div class="value">
            {{ form.ascriptionType === 1 ? '商用' : form.ascriptionType === 1 ? '家用' : ''  }}
          </div>
        </div>
        <!-- <div class="info_item">
          <div class="label">拨打电话:</div>
          <div class="value">
            <template v-if="form.callPhoneType == 0">关闭</template>
            <template v-else>必须拨打</template>
          </div>
        </div> -->
      </div>
    </div>

    <!-- 编辑弹窗 -->
    <EditOrModuleModal
      mode="edit"
      title="编辑模块"
      :module-id="(route.params.id as string)"
      :visible="modalVisible"
      :is-show-del-btn="false"
      @delete="deleteModule"
      @close="modalVisible = false"
      @updated="getDetail"
    />

    <!-- 列表 -->
    <div class="body" :style="bodyStyle">
      <el-tabs v-model="activeName" @tab-click="switchTabs">
        <el-tab-pane label="工单分类" name="type">
          <TypeCard ref="typeCard" />
        </el-tab-pane>
        <el-tab-pane label="处理方式" name="handle">
          <HandleCard ref="handleCard" />
        </el-tab-pane>
        <el-tab-pane label="结单字段" name="finish">
          <FinishCard ref="finishCard" />
        </el-tab-pane>
        <!--后续可能会用到-->
        <!--<el-tab-pane label="回访字段" name="eval">-->
        <!--  <EvalCard ref="evalCard" />-->
        <!--</el-tab-pane>-->
        <el-tab-pane label="工单字段" name="field">
          <FieldCard ref="filedCard" />
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, watch, CSSProperties } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import type { FormInstance } from 'element-plus'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { TabsPaneContext } from 'element-plus'
  import TypeCard from './components/TypeCard/index.vue'
  import HandleCard from './components/HandleCard/index.vue'
  import FinishCard from './components/FinishCard/index.vue'
  import FieldCard from './components/FieldCard/index.vue'
  import {
    moduleSave,
    moduleGetDetail,
    moduleDelete,
    workClientStrategyPageSelect,
  } from '@/api/basic'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import { PRIMARY_COLOR } from '@/config'
  import EditOrModuleModal from '../components/ModuleCard/EditOrModuleModal.vue'
  import routeComponentName from '@/config/route-component-name'

  defineOptions({
    name: routeComponentName.setting.orderModuleDetailSet,
  })

  const activeName = ref('type')
  const TagsViewStore = useTagsViewStore()
  const route = useRoute()
  const router = useRouter()
  const loading = ref(false)

  const formRef = ref<FormInstance>() // 表单元素

  // 弹窗显示状态
  const modalVisible = ref(false)

  const typeCard = ref()
  const handleCard = ref()
  const filedCard = ref()
  const finishCard = ref()
  const evalCard = ref()
  const workClientStrategyName = ref() // 分配客服规则搜索名称
  const clientStrategyOption = ref([]) // 分配客服规则下拉数据

  const tagsViewStore = useTagsViewStore()
  const infoListRef = ref<HTMLDivElement | null>(null)
  const bodyStyle = ref<CSSProperties>({})
  const setBodyStyle = () => {
    if (infoListRef.value) {
      bodyStyle.value.height = `calc(100% - 12px - 12px - 78px - ${infoListRef.value.scrollHeight}px)`
    }
  }

  // 表单数据
  const form = ref({
    id: '',
    name: '',
    enableWarrantyOrder: true,
    overinsured: false, // 质保状态，是否保外：false-保内，true-保外
    inSourcingPrice: 0, // 保内费用
    outSourcingPrice: 0, // 保外费用
    price: 0,
    status: false,
    reservationTimeType: 2, // 预约时间类型：1-不启用，2-24小时，3-预约时间范围
    reservationStartTime: '', // 预约开始时间，仅传小时
    reservationEndTime: '', // 预约结束时间，仅传小时
    type: 1,
    warrantyDay: 30,
    autoDispatchClient: true, // 	是否自动分配客服：false-否，true-是
    workClientStrategyId: '', // 工单客服分派策略ID
    autoDispatchNetwork: true, // 	是否自动分配网点：false-否，true-是
    mobileCreateOrderShow: true, // 是否移动报单端展示：false-不显示，true-显示
    enableStatementVerifCode: true, //是否启用结单核销码：false-不启用，true-启用,示例值(true)
    statementVerifCodeType: 1, //结单核销码类型：1-随机，2-固定；当enableStatementVerifCode=true时生效,示例值(1)
    statementVerifCode: '', //结单核销码：当verifCodeType=2时生效
    callPhoneType: 0, // 拨打电话类型：0-关闭，1-必须拨打
    workSlaId: '',
    slaName: '',
    enableSign: true,
    enableSuspend: true,
    createTime: null, // 创建时间
    updateTime: null, // 更新时间
    ascriptionType: 0 // 1:商业  2:家用
  })

  // 验证规则
  const rules = reactive({
    name: [{ required: true, message: '请输入模块名称', trigger: 'blur' }],
    inSourcingPrice: [
      { required: true, message: '请输入保内费用', trigger: ['blur', 'change'] },
      {
        pattern: /^0$|^0\.\d{1,2}$|^[1-9]{1}\d{0,6}(\.\d{1,2})?$/g,
        message: '仅允许输入7位整数，或输入7位整数带两位小数',
        trigger: ['blur', 'change'],
      },
    ],
    outSourcingPrice: [
      { required: true, message: '请输入保外费用', trigger: ['blur', 'change'] },
      {
        pattern: /^0$|^0\.\d{1,2}$|^[1-9]{1}\d{0,6}(\.\d{1,2})?$/g,
        message: '仅允许输入7位整数，或输入7位整数带两位小数',
        trigger: ['blur', 'change'],
      },
    ],
    warrantyDay: [
      { required: true, message: '请输入质保天数', trigger: ['blur', 'change'] },
      {
        pattern: /^0$|^[1-9]{1}\d{0,5}$/g,
        message: '质保天数输入错误，请输入 >=0 的六位整数',
        trigger: ['blur', 'change'],
      },
    ],
  })

  // 初始化表单
  const initForm = () => {
    form.value = {
      id: '',
      name: '',
      enableWarrantyOrder: true,
      overinsured: false, // 质保状态，是否保外：false-保内，true-保外
      inSourcingPrice: 0, // 保内费用
      outSourcingPrice: 0, // 保外费用
      price: 0,
      status: false,
      reservationTimeType: 2, // 预约时间类型：1-不启用，2-24小时，3-预约时间范围
      reservationStartTime: '', // 预约开始时间，仅传小时
      reservationEndTime: '', // 预约结束时间，仅传小时
      type: 1,
      warrantyDay: 30,
      autoDispatchClient: true, // 	是否自动分配客服：false-否，true-是
      workClientStrategyId: '', // 工单客服分派策略ID
      autoDispatchNetwork: true, // 	是否自动分配网点：false-否，true-是
      mobileCreateOrderShow: true,
      enableStatementVerifCode: true, //是否启用结单核销码
      statementVerifCodeType: 1, //结单核销码类型
      statementVerifCode: '', //结单核销码
      workSlaId: '',
      slaName: '',
      enableSign: true,
      enableSuspend: true,
      createTime: null, // 创建时间
      updateTime: null, // 更新时间
      callPhoneType: 0, // 拨打电话类型：0-关闭，1-必须拨打
    }
  }

  // 获取模块详情加载状态
  const getDetailLoading = ref(false)

  // 当前操作的方式：del-删除，edit-编辑
  // 如果是删除的话删除成功就返回上一页，编辑成功的话留在当前页面但是要更新数据
  const currentOperateMode = ref<'edit' | 'del'>('edit')

  // 获取模块详情
  const getDetail = async () => {
    initForm()
    getDetailLoading.value = true
    await moduleGetDetail(route.params.id).then((res) => {
      getDetailLoading.value = false
      form.value = res.data.data.row
    })
  }

  // 删除模块
  const deleteModule = () => {
    currentOperateMode.value = 'del'
    saveDataMethod('删除', moduleDelete, [route.params.id])
  }

  // 编辑模块
  const editModule = () => {
    currentOperateMode.value = 'edit'
    modalVisible.value = true
  }

  // 取消修改
  const cancelEdit = () => {
    TagsViewStore.delView(router.currentRoute.value.path)
    if (currentOperateMode.value === 'edit') {
      getDetail()
      modalVisible.value = false
    } else {
      router.push({ path: '/busic/base/orderset', query: { active: 'module' } })
    }
  }

  // 保存方法
  const saveDataMethod = (type, method, data) => {
    ElMessageBox({
      type: type == '删除' ? 'error' : 'warning',
      title: '提示',
      message: `确认${type}该模块?`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 1000)
        } else {
          done()
        }
      },
    }).then(async () => {
      method(data).then((res) => {
        if (res.data.success == true) {
          ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 5000,
            plain: true,
            showClose: true,
          })
          cancelEdit()
        } else {
          ElMessage({
            message: res.data.message,
            type: 'warning',
            duration: 5000,
            plain: true,
            showClose: true,
          })
          return
        }
      })
    })
  }

  // 保存模块
  const saveModule = (form) => {
    if (form.reservationTimeType == 3 && (!form.reservationStartTime || !form.reservationEndTime)) {
      ElMessage({
        message: '预约时间范围不能为空',
        type: 'warning',
        duration: 5000,
        plain: true,
        showClose: true,
      })
      return
    }
    delete form.createTime
    delete form.updateTime
    saveDataMethod('修改', moduleSave, form)
  }

  // 客服分配规则远程搜索
  const workClientStrategyRemoteMethod = (name: string) => {
    workClientStrategyName.value = name
  }

  // 获取分配客服规则Api
  const clientStrategyApi = async () => {
    const searchData = {
      limit: 50,
      name: workClientStrategyName.value,
      page: 1,
    }
    await workClientStrategyPageSelect(searchData).then((res) => {
      clientStrategyOption.value = res.data.data.rows
    })
  }

  // 选项切换
  const switchTabs = (tab: TabsPaneContext) => {
    switch (tab.props.name) {
      case 'type':
        typeCard.value.getList()
        break
      case 'handle':
        handleCard.value.getList()
        break
      case 'finish':
        finishCard.value.getList()
        break
      case 'eval':
        evalCard.value.getList()
        break
      case 'field':
        filedCard.value.getList()
        break
    }
  }

  // 监听客服分配规则远程搜索
  watch(
    () => workClientStrategyName.value,
    (newVal, oldVal) => {
      if (!oldVal && newVal === '') {
        return
      }
      clientStrategyApi()
    },
  )

  watch(
    () => tagsViewStore.getReloadPages,
    (value) => {
      if (value.includes(route.path)) {
        window.removeEventListener('resize', setBodyStyle)
      }
    },
    { immediate: true, deep: true },
  )

  watch(route, (value) => {
    if (value.name === 'moduleDetail') {
      // 当重新进入页面时数据要更新，否则外部更新了数据里面没更新
      getDetail()
      typeCard.value.getList()
      clientStrategyApi()
    } else {
      // 页面离开时要关闭弹窗否则，否则重新进入的话弹窗就会显示
      modalVisible.value = false
    }
  })

  onMounted(() => {
    getDetail()
    typeCard.value.getList()
    clientStrategyApi()
    setBodyStyle()
    window.addEventListener('resize', setBodyStyle)
  })
</script>

<style scoped lang="scss">
  @import './index.scss';
</style>
